package controllers

import (
	"chatroom/chat"
	"chatroom/models"
	"github.com/astaxie/beego"
	"log"
	"net/http"
	"reflect"
)

type UserController struct {
	beego.Controller
}

var hub *chat.Hub

func init() {
	hub = chat.NewHub()
	go hub.BeginRun()
}

/**提供Websocket服务端的Endpoint*/
func (this *UserController) RegisterClient() {
	//注册客户端
	user := this.GetSession("user")
	var username string
	user = user.(models.User)
	username = reflect.ValueOf(user).FieldByName("Username").String()
	log.Println("RegisterClient.....")
	//登录成功后设置用户的登录状态
	uid := reflect.ValueOf(user).FieldByName("Id").Int()
	nuser := &models.User{Id: uid, Islogin: true}
	models.SetLoginState(nuser)
	//注册客户端到hub中
	w := this.Ctx.ResponseWriter.ResponseWriter
	r := this.Ctx.Request
	chat.RegisterClient(w, r, hub, username)
	this.ServeJSON()
}

func (this *UserController) Login() {
	user := models.User{}
	if err := this.ParseForm(&user); err != nil {
		log.Println("表单解析错误:", err)
	} else { //表单解析成功
		log.Println("用户提交的数据:", user)
		dbUser := models.GetUserByUser(&user)
		if dbUser.Id != 0 { //登录成功
			// 设置session
			this.SetSession("user", dbUser)
			//重定向到系统首页
			this.Ctx.Redirect(http.StatusFound, "/static/index.html")
			return
		}
	}
	this.Ctx.Redirect(http.StatusFound, "/static/login.html")
}

/**注册用户信息*/
func (this *UserController) Register() {
	user := models.User{}                         //返回的不是地址
	if err := this.ParseForm(&user); err != nil { //解析表单
		log.Println("表单解析错误:", err)
	} else { //正确解析表单数据
		models.AddUser(&user) //添加用户信息
	}
	this.Ctx.Redirect(http.StatusFound, "/static/login.html")
}

/**获取用户列表*/
func (this *UserController) List() {
	users := models.List()
	this.Data["json"] = &users
	log.Println("获取登录的用户列表信息")
	this.ServeJSON()
}

/**用户退出，注销*/
func (this *UserController) Logout() {
	this.DelSession("user")
	this.Ctx.Redirect(http.StatusFound, "/static/login.html")
}
